﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,ConcurrencyMode=ConcurrencyMode.Multiple)]
public class Service : IService
{
    private List<Chater> clients = new List<Chater>();
    static string msg = string.Empty;
    public void AddNewClient(string nickname)
    {
        System.IO.StreamWriter sw = new System.IO.StreamWriter("logfile.txt");
        sw.WriteLine("file created");
        IClient newClient = OperationContext.Current.GetCallbackChannel<IClient>();
        sw.WriteLine("CallbackChanell got");
        if (clients.Count != 0)
        {
            sw.WriteLine("entered in if. number of clients - " + clients.Count);
            foreach (Chater chater in clients)
            {
                sw.WriteLine("Entered in first foreach");
                chater.UpdateContacts(nickname);
                sw.WriteLine("1 Update contacts done");
            }
            foreach (Chater chater in clients)
            {
                sw.WriteLine("Enterd in second foreach");
                newClient.UpdateContacts(chater.Nickname);
                sw.WriteLine("2 update constacts done");
            }
        }
        sw.WriteLine("exited from foreach");
        sw.WriteLine("trying to call clients.Add");
        clients.Add(new Chater(newClient, nickname));
        sw.WriteLine("clients add ok...quiting method");
        sw.Dispose();
    }


    public void SendMessageToService(string message, string nickname)
    {
        msg = message;
        foreach (Chater chater in clients)
        {
            if (chater.Nickname.Equals(nickname))
            {
                chater.SendMessageToClient(message);
                return;
            }
        }
    }


    public void DisconnectFromServer(string nickname)
    {
        foreach (Chater chater in clients)
        {
            if (chater.Nickname.Equals(nickname))
            {
                clients.Remove(chater);
                return;
            }
        }
    }
}

public class Chater
{
    private IClient _client = null;
    private string _nickname = string.Empty;
    public Chater(IClient newClient, string nickname)
    {
        _client = newClient;
        _nickname = nickname;
    }

    public string Nickname
    {
        get
        {
            return _nickname;
        }
    }

    public void SendMessageToClient(string message)
    {
        _client.SendMessageToClient(message);
    }

    public void UpdateContacts(string nickname)
    {
        _client.UpdateContacts(nickname);
    }
}